package com.boe.config.spring;

import com.boe.common.mvc.LoginUserModel;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 当前请求上下文
 */
public class HttpContext {
    private static ThreadLocal<HttpServletRequest> filterRequest = ThreadLocal.withInitial(null);
    private static ThreadLocal<HttpServletResponse> filterResponse = ThreadLocal.withInitial(null);

    /**
     * 在全局Filter中设置当前请求响应。
     *
     * @param request
     * @param response
     */
    public static void init(HttpServletRequest request, HttpServletResponse response) {
        filterRequest.set(request);
        filterResponse.set(response);
    }

    /**
     * 获取当前请求
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        var requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getRequest();
        }

        return filterRequest.get();
    }


    /**
     * 获取当前响应
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        var requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            return requestAttributes.getResponse();
        }

        return filterResponse.get();
    }

    public static void setLoginUser(LoginUserModel loginUser) {
        getRequest().setAttribute("[LoginUser]", loginUser);
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static LoginUserModel getLoginUser() {
        return (LoginUserModel) getRequest().getAttribute("[LoginUser]");
    }
}
